package com.ccloud.auth.core.utils;

import com.ccloud.api.system.domain.SysUser;
import com.ccloud.api.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author chentailai
 */
@Component
@Slf4j
public class SecurityUtil {


    @Resource
    private ISysUserService userService;

    /**
     * 获取当前登录用户
     * @return
     */
    public SysUser getCurrUser() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || authentication.getName() == null
                || authentication instanceof AnonymousAuthenticationToken) {
            throw new RuntimeException("未检测到登录用户");
        }
        return userService.getUserByName(authentication.getName());
    }

}
